/**
 * 获取用户消费记录列表接口
 */

//引入Q模块
let Q = require('q');

let redis;

//updateProfile入口函数
let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	redis = _redis
	if(postData.year && postData.month) {
		getUserId(postData._3rdSession).then(function(userId) {
			//本月起始时间
			let startTimestamp = parseInt(new Date(postData.year + '/' + postData.month + '/1').getTime() / 1000);
			//下月起始时间
			let endTimestamp = parseInt(new Date(postData.year + '/' + (postData.month + 1) + '/1').getTime() / 1000);
			return db.select('storeOrder', {
				userId: userId,
				timestamp: {
					$gte: startTimestamp,
					$lte: endTimestamp
				}
			});
		}, function() {
			//获取用户ID失败
			deferred.reject('-0081');
		}).then(function(orderList) {
			deferred.resolve(orderList);
		}, function() {
			//查询用户消费订单列表失败
			deferred.reject('-0200');
		});
	}
	else {
		//获取用户消费记录列表接口参数不足
		deferred.reject('-0199');
	}
	return deferred.promise;	
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		if(data) {
			data = JSON.parse(data);
			if(data.openId) {
				deferred.resolve(data.openId);
			}
			else {
				deferred.reject();
			}
		}
		else {
			deferred.reject();
		}
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};

